package com.joint.web.action.party;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.DataUtil;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.Department;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.RoleService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.LetterRegister;
import com.joint.core.service.LetterRegisterService;
import com.joint.web.action.BaseFlowAction;
import com.opensymphony.xwork2.ActionContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("party")
public class AjaxLetterregisterAction extends BaseFlowAction {
   
   
    @Resource
    private LetterRegisterService letterRegisterService;
   
    @Resource
    private DepartmentService departmentService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private RoleService roleService;


    private LetterRegister letterRegister;
    private List<Map<String,Object>> postArrayList;

    private int numStatus;
    private Users loginUser;

    //前台传到后台的数据
    private String letterTypeId;

    //从后台传回前台的数据


    //申请人信息
    private String applyUserName;
    private String applyUserId;
    private String applyUserDate;



    /**
     * 信访类型
     */
    private Dict letterType;
    /**
     *信访开始日期
     */
    private Date letterStartDate;
    /**
     * 信访结束日期
     */
    private Date letterEndDate;
    /**
     * 信访件处理结果
     */
    private BigDecimal workSummary;

    /**
     * 信访件处理评价
     */
    private String letterEvaluate;


    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "letterregister";
    }


    public String listfordialog(){

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        pager=letterRegisterService.findByPagerAndProcessState(pager, user, "letterregister", FlowEnum.ProcessState.Finished, params);
        List<LetterRegister> letterRegisterList;
        if (pager.getTotalCount() > 0){
            letterRegisterList = (List<LetterRegister>) pager.getList();
        }else{
            letterRegisterList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(LetterRegister letterRegister:letterRegisterList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",letterRegister.getId()!=null?letterRegister.getId():"");
            rMap.put("creater",letterRegister.getCreater()!=null?letterRegister.getCreater().getName():"");
            rMap.put("selectDate",letterRegister.getCreateDate()!=null?new SimpleDateFormat("yyyy-MM-dd").format(letterRegister.getCreateDate()):"");
            String temp="";
            /*if(letterRegister.getLetterRegisterDetailList()!=null){
                for (LetterRegisterDetail letterRegisterDetail:letterRegister.getLetterRegisterDetailList()){
                    temp+=letterRegisterDetail.getLetterRegisterItem().getName()+",";
                }
                rMap.put("dictName",temp);
            }else {
                rMap.put("dictName","");
            }
            rMap.put("letterRegisterMoney",letterRegister.getLetterRegisterMoney()!=null?letterRegister.getLetterRegisterMoney().toString():"");
            rMap.put("departmentName",letterRegister.getDepartment()!=null?letterRegister.getDepartment().getName():"");*/
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }
    public Map getSearchFilterParams(String _search,Map<String,Object> params,String filters){
        //createAlias Key集合
        List<String> alias = new ArrayList<String>();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(_search)){
            boolean __search = Boolean.parseBoolean(_search);
            if(__search&& org.apache.commons.lang3.StringUtils.isNotEmpty(filters)){
                JSONObject filtersJson = JSONObject.fromObject(filters);
                if(org.apache.commons.lang3.StringUtils.equals(filtersJson.getString("groupOp"), "AND")){
                    //查询条件
                    JSONArray rulesJsons = filtersJson.getJSONArray("rules");
                    //遍历条件
                    for(int i=0;i<rulesJsons.size();i++){
                        JSONObject rule = rulesJsons.getJSONObject(i);
                        if(rule.has("field")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("field"))&&rule.has("data")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                            String field = rule.getString("field");
                            if(field.contains("_")){
                                String[] fields = field.split("_");
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    params.put(field.replaceAll("_", "."), rule.getString("data"));
                                }
                            }else{
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    if(field.equals("letterStartDate")){
                                        params.put("letterStartDate", com.joint.base.util.DataUtil.StringToDate(rule.getString("data")));
                                    } else {
                                        params.put(field, rule.getString("data"));
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }

        return params;
    }
    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        loginUser = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=letterRegisterService.findByPagerAndLimit(false, "letterregister", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=letterRegisterService.findByPagerAndFinish("letterregister", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=letterRegisterService.findByPagerAndLimit(true, "letterregister", pager, params);
        }

        List<LetterRegister> letterRegistersList;
        if (pager.getTotalCount() > 0){
            letterRegistersList = (List<LetterRegister>) pager.getList();
        }else{
            letterRegistersList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(LetterRegister letterRegister:letterRegistersList){

            SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
            rMap = new HashMap<String,Object>();
            rMap.put("id",letterRegister.getId()!=null?letterRegister.getId():"");
            rMap.put("year",letterRegister.getYear()!=null?letterRegister.getYear():"");
            rMap.put("month",letterRegister.getMonth()!=null?letterRegister.getMonth():"'");
           /* if(letterRegister.getCreateDate()!=null){
                String year=new SimpleDateFormat("yyyy").format(letterRegister.getCreateDate());
                String month=new SimpleDateFormat("MM").format(letterRegister.getCreateDate());
                rMap.put("year",year);
                rMap.put("month",month);
            }else{
                rMap.put("year","");
                rMap.put("month","");
            }*/
           /* if(letterRegister.getLetterStartDate()!=null&&letterRegister.getLetterEndDate()!=null){
                rMap.put("letterStart",new SimpleDateFormat("yyyy-MM-dd").format(letterRegister.getLetterStartDate())+" --> "+new SimpleDateFormat("yyyy-MM-dd").format(letterRegister.getLetterEndDate()));
            }else{
                rMap.put("letterStart","");
            }*/
            rMap.put("letterStartDate",letterRegister.getLetterStartDate()!=null?new SimpleDateFormat("yyyy-MM-dd").format(letterRegister.getLetterStartDate()):"");
            rMap.put("letterType",letterRegister.getLetterType()!=null?letterRegister.getLetterType().getName():"");
            rMap.put("state",letterRegister.getProcessState().value()!=null?letterRegister.getProcessState().value():"");




            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){

        letterType=new Dict();

        if(StringUtils.isNotEmpty(keyId)) {
            loginUser=usersService.getLoginInfo();
            letterRegister = letterRegisterService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            //信访类型
            if(letterRegister.getLetterType()!=null){
                letterType=letterRegister.getLetterType();
            }
        }else{

        }
        return "read";
    }

    public String input(){
        letterType=new Dict();
        if (StringUtils.isNotEmpty(keyId)){

            letterRegister = letterRegisterService.get(keyId);
            loginUser=usersService.getLoginInfo();
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            //信访类型
            if(letterRegister.getLetterType()!=null){
                letterType=letterRegister.getLetterType();
            }
            //申请人信息

            applyUserName=usersService.getLoginInfo().getName();
            applyUserId=usersService.getLoginInfo().getId();
            applyUserDate=new SimpleDateFormat("yyyy-MM-dd").format(letterRegister.getCreateDate());
        } else {


        }




        return "input";
    }

    private void setData(){

        if(StringUtils.isNotEmpty(keyId)){
            letterRegister = letterRegisterService.get(keyId);
        }else{
            letterRegister = new LetterRegister();
            letterRegister.setCreater(usersService.getLoginInfo());

        }

        //信访类型
        if(StringUtils.isNotEmpty(letterTypeId)){
            letterType=dictService.get(letterTypeId);
        }


        letterRegister.setLetterType(letterType);
        letterRegister.setLetterStartDate(letterStartDate);
        letterRegister.setLetterEndDate(letterEndDate);
        letterRegister.setWorkSummary(workSummary);
        letterRegister.setLetterEvaluate(letterEvaluate);
        letterRegister.setCreater(usersService.getLoginInfo());
        letterRegister.setCompany(usersService.getLoginInfo().getCompany());
        Date date=new Date();
        letterRegister.setYear(new SimpleDateFormat("yyyy").format(date));
        letterRegister.setMonth(new SimpleDateFormat("MM").format(date));
        letterRegisterService.save(letterRegister);

    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                letterRegisterService.update(letterRegister);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                letterRegisterService.save(letterRegister, "letterregister", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();

        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        if(StringUtils.isEmpty(comment)){
            comment="";
        }

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                letterRegisterService.approve(letterRegister, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                letterRegisterService.commit(letterRegister, "letterregister", var1, var2, curDutyId);/*返回文档的iD*/
               /* LogUtil.info("KeyId_2 = "+keyId);
                LetterRegister entity = letterRegisterService.get(keyId);*//*文档id*//*
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                letterRegisterService.save(entity);
*/

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        letterRegister = letterRegisterService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                letterRegisterService.approve(letterRegister, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        letterRegister = letterRegisterService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        //  var2.put("curDutyId", curDutyId);
        try {
            letterRegisterService.approve(letterRegister, FlowEnum.ProcessState.Finished, var2, curDutyId, comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        letterRegister = letterRegisterService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            letterRegisterService.approve(letterRegister, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            letterRegister = letterRegisterService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("letterregister");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            letterRegisterService.reject(letterRegister, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            letterRegister = letterRegisterService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("letterregister");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            letterRegisterService.deny(letterRegister, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public LetterRegister getLetterRegister() {
        return letterRegister;
    }

    public void setLetterRegister(LetterRegister letterRegister) {
        this.letterRegister = letterRegister;
    }











    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }


    public String getViewtype() {


        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public List<Map<String, Object>> getPostArrayList() {
        return postArrayList;
    }

    public void setPostArrayList(List<Map<String, Object>> postArrayList) {
        this.postArrayList = postArrayList;
    }

    public String getApplyUserName() {
        return applyUserName;
    }

    public void setApplyUserName(String applyUserName) {
        this.applyUserName = applyUserName;
    }

    public String getApplyUserId() {
        return applyUserId;
    }

    public void setApplyUserId(String applyUserId) {
        this.applyUserId = applyUserId;
    }


    public String getApplyUserDate() {
        return applyUserDate;
    }

    public String getLetterTypeId() {
        return letterTypeId;
    }

    public void setLetterTypeId(String letterTypeId) {
        this.letterTypeId = letterTypeId;
    }

    public void setApplyUserDate(String applyUserDate) {
        this.applyUserDate = applyUserDate;
    }

    public Dict getLetterType() {
        return letterType;
    }

    public void setLetterType(Dict letterType) {
        this.letterType = letterType;
    }



    public BigDecimal getWorkSummary() {
        return workSummary;
    }

    public void setWorkSummary(BigDecimal workSummary) {
        this.workSummary = workSummary;
    }

    public Date getLetterStartDate() {
        return letterStartDate;
    }

    public void setLetterStartDate(Date letterStartDate) {
        this.letterStartDate = letterStartDate;
    }

    public Date getLetterEndDate() {
        return letterEndDate;
    }

    public void setLetterEndDate(Date letterEndDate) {
        this.letterEndDate = letterEndDate;
    }

    public String getLetterEvaluate() {
        return letterEvaluate;
    }

    public void setLetterEvaluate(String letterEvaluate) {
        this.letterEvaluate = letterEvaluate;
    }
}


